package data

import (
	"context"

	protoV1 "Cosmos.Communication/api/v1"
	"Cosmos.Communication/internal/biz"
	"github.com/go-kratos/kratos/v2/log"
	"google.golang.org/protobuf/types/known/wrapperspb"
)

type notify struct {
	infrastructure *Data
	logHelper      *log.Helper
}

func NewNotify(data *Data, logger log.Logger) (d biz.Notify, cf func(), err error) {
	instance := &notify{
		infrastructure: data,
	}
	instance.logHelper = log.NewHelper(logger)

	cf = instance.Close
	err = nil
	d = instance
	return
}

func (i *notify) Notify(ctx context.Context, request *biz.NotifyRequest) (result *biz.Result[*biz.NotifyResponse], err error) {
	result = &biz.Result[*biz.NotifyResponse]{
		Code: 200,
	}

	go i.NotifyVendor(ctx, request)
	return
}

func (i *notify) Close() {
	i.infrastructure.Close()
}

func (i *notify) NotifyVendor(ctx context.Context, request *biz.NotifyRequest) {
	i.logHelper.Info("开始通知小核")
	client, err := i.infrastructure.GetVendorRuntimeGrpcClient()
	if err != nil {
		i.logHelper.Error("通知小核失败：", err)
		return
	}

	rpcRequest := &protoV1.Notification{
		Topic:      &wrapperspb.StringValue{Value: request.Topic},
		RoutingKey: &wrapperspb.StringValue{Value: request.RoutingKey},
		Message:    &wrapperspb.StringValue{Value: request.Message},
	}

	rpcResult, err := client.Notify(ctx, rpcRequest)
	if err != nil {
		i.logHelper.Error("通知小核失败：", err)
		return
	}
	if rpcResult == nil {
		i.logHelper.Error("通知小核失败!", "RpcResult is nil")
		return
	}

	result := &biz.Result[*biz.NotifyResponse]{
		Code:    int(rpcResult.Code),
		Message: rpcResult.Message.GetValue(),
		Data:    &biz.NotifyResponse{},
	}
	i.logHelper.Info("通知小核完成:", result.Code, result.Data, result.Message)
}
